import matplotlib.pyplot as plt
import numpy as np
import time

def sumReal(data, f):
    a = []
    l = len(data)
    n = 0
    while(n!=l):
        a.append(data[n]*np.cos(2*np.pi*f*n)) # x(n)*cos(2*Pi*f*n) : f is based on HZ
        n = n + 1
    return sum(a)

def sumIma(data, f):
    a = []
    l = len(data)
    n = 0
    while(n!=l):
        a.append(data[n] * (-(np.sin(2*np.pi*f*n))))
        n = n + 1
    return sum(a)



data = []
def dtft(f):
    l = len(data)
    realWhole = sumReal(data, f)
    imaWhole = sumIma(data, f)
    return np.sqrt(realWhole * realWhole + imaWhole * imaWhole)

def p(x, y, filename):
    plt.plot(x, y)
    plt.xlabel('f')
    plt.ylabel('fudu')
    plt.grid(True)
    plt.savefig(filename+".dtft.png")
    plt.show()
def saveImg(x, y, filename):
    plt.plot(x, y)
    plt.xlabel('f')
    plt.ylabel('fudu')
    plt.grid(True)
    plt.savefig(filename+".dtft.png")
    plt.close('all')

def dtftAll(filename, logpath):
    filee = open(filename)
    i = 1
    for line in filee:
        global data 
        data = []
        rawdata = line.rsplit(sep=',')
        fname = logpath + rawdata[0]
        data = [int(x) for x in rawdata[1:]]
        data = np.array(data)
        data = data - data.sum()/len(data) # 去直流分量
        saveImg(np.linspace(0,len(data), len(data)), data, fname + ".data")
        
        f = np.linspace(0.015, 0.1, 300)
        vfunc = np.vectorize(dtft)
        X = vfunc(f)

        # 归一化
        sumofX = X.sum()
        nX = X
        if(sumofX != 0):
            nX = X/sumofX
        
        huanyuandu = nX[np.argsort(nX)][len(nX)-35:].sum()
        print(i, huanyuandu, fname)
        i = i+1
        saveImg(f, nX, fname + '_' + str(huanyuandu) + '_')

    filee.close()

# dtftAll("/Users/wangsiyuan/code/leecode/js/learnangular/ohters/20160731data.log", "./log/")

dtftAll("./weishuju/weishuju.txt", "./weilog/")


